<template>
  <div class="searchContainer">
    <!-- 版头 搜索框 -->
    <form action="/" class="search-box">
      <van-search
        v-model="searchText"
        show-action
        background="#e11c34"
        placeholder="请输入搜索关键词"
        @clear="onClear"
        @search="onSearch"
        @cancel="onCancel"
      />
    </form>

    <!-- 搜索结果 -->
    <search-result :search-text="searchText" v-if="resultShow" />
    <!-- /搜索结果 -->

    <!-- 搜索建议 -->
    <search-suggestion
      @search="onSearch"
      :search-text="searchText"
      v-else-if="searchText"
    />
    <!-- /搜索建议 -->

    <!-- 搜索历史&热门搜索 -->
    <search-history
      @search="onSearch"
      :search-histories="SearchHistories"
      v-else
    ></search-history>
    <!-- 搜索历史 -->
  </div>
</template>

<script>
import SearchSuggestion from './components/searchSuggestion.vue'
import SearchResult from './components/searchResult.vue'
import SearchHistory from './components/searchHistory.vue'
import { setItem, getItem } from '@/utils/storage'
export default {
  components: { SearchSuggestion, SearchResult, SearchHistory },
  name: 'Search',
  data() {
    return {
      searchText: '', // 输入文字
      SearchHistories: getItem('TOUTIAO_HISTORY') || [], // 搜索历史列表
      resultShow: false, // 是否出现搜索结果
    }
  },
  watch: {
    SearchHistories: {
      deep: true,
      handler() {
        console.log(this.SearchHistories);
        setItem('TOUTIAO_HISTORY', this.SearchHistories)
      },
    },
  },
  methods: {
    // 搜索行为
    onSearch(val) {
      // 去重
      let idx = this.SearchHistories.findIndex((item) => item === val)
      if (idx !== -1) this.SearchHistories.splice(idx, 1)
      // 放入
      this.SearchHistories.unshift(val)
      this.resultShow = true
      this.searchText = val
    },
    // 取消搜索
    onCancel() {
      this.$router.back()
    },
    onClear() {
      this.searchText = ''
      this.resultShow = false
    },
  },
}
</script>

<style lang="less" scoped>
// .search-box{
//   width: 100%;
//   position: fixed;
//   top: 0;
//   z-index: 11;
//   margin-bottom: 55px;
// }
.searchContainer {
  background: #eeeeee;
  height: 100%;
}
.searchHistory {
  margin-bottom: 20px;
}

/deep/ .van-search__action {
  color: #fff !important;
}
</style>
